<?php

namespace app\common\model;

use think\Collection;
use PDOStatement;
use think\exception\DbException;
use think\db\exception\ModelNotFoundException;
use think\db\exception\DataNotFoundException;
use think\Model;

/**用户答题 */
class UserAnswers extends Model
{
    // 表名
    protected $name = 'user_answers';

    /**
     * 用户答题
     * @param mixed $params 
     * @return bool 
     * @throws DbException 
     * @throws ModelNotFoundException 
     * @throws DataNotFoundException 
     */
    public function saveUserAnswers($params)
    {
        # 查询题库
        $info = Question::where('id', $params['question_id'])->field('id,mock_id,kind')->find();
        if (empty($info)) fail('题库不存在');
        # 查询是否答过该题目
        $infoQuestionUserAnswers = self::where([
            'user_id' => $params['user_id'],
            'question_id' => $params['question_id'],
            'question_group_id' => $params['question_group_id'],
            'type' => '0'
        ])->find();
        # 主观题 判定
        if ($info->kind == "SHORT" && $params['is_right'] != '3') {
            fail("主观题传is_right参数错误");
            return false;
        }
        # 数据整理
        $data = [
            'user_id' => $params['user_id'],
            'mock_id' => $info->mock_id,
            'question_group_id' => $params['question_group_id'],
            'question_id' => $params['question_id'],
            'answer' => $params['answer'],
            'is_right' => $params['is_right'],
            'imgs' => $params['imgs'],
            'type' => isset($params['type']) ? $params['type'] : 0, // 默认刷题类型
            'create_time' => time(),
        ];
        if (!empty($infoQuestionUserAnswers)) {
            $data['update_time'] = time();
            $res = self::where('id', $infoQuestionUserAnswers->id)->update($data);
        } else {
            $data['in_error'] = $params['is_right'] == 0 ? 1 : 0;
            $res = self::insert($data);
        }
        if ($res) return true;
        return false;
    }


    /**错误集 */
    public function getListUserAnswers($user_id, $extend = [])
    {
        $where['user_id'] = $user_id;
        $answers = self::where($where)
            ->field('id as question_user_answers_id,question_id,answer,is_right,imgs')
            ->select();
        $questionUserAnswers = [];
        foreach ($answers as $answer) {
            $questionUserAnswers[$answer['question_id']] = $answer;
        }
        return $questionUserAnswers;
    }

    /**
     * 模块错误集
     * @param mixed $user_id 
     * @param mixed $mock_id 
     */
    public function getErrorList($user_id, $mock_id, $photograph = 0)
    {
        $where['user_id'] = $user_id;
        if ($mock_id) {
            $where['mock_id'] = $mock_id;
        }
        if ($photograph == 1) {
            $where['type'] = ['in', [0, 1]];
        }
        $where['in_error'] = 1;
        $list = self::where($where)
            ->field('id as question_user_answers_id,question_id,answer,is_right,imgs,type,photo_img')
            ->select();
        if (empty($list)) return [];
        $result = [];
        foreach ($list as $answer) {
            if ($answer['type'] == 2) {
                // 拍照上传题 - 没有question_id，需要特殊处理
                $photoQuestion = [
                    'question_id' => 'photo_' . $answer['question_id'], // 生成唯一标识
                    'kind' => 'PHOTO', // 标记为拍照题类型
                    'title' => '拍照上传题',
                    'explain' => '',
                    'difficulty' => 'GENERAL',
                    'options_json' => [],
                    'options_img' => '',
                    'answer' => '',
                    'status' => 'NORMAL',
                    'user_answer' => ['answer' => '', 'imgs' => $answer['photo_img']],
                    'is_right' => $answer['is_right'],
                    'question_user_answers_id' => 'photo_' . $answer['question_user_answers_id'],
                    'photo_img' => $answer['photo_img'],
                    'type' => $answer['type']
                ];
                $result[] = $photoQuestion;
            } else {
                // 普通题目 - 有question_id，查询题库信息
                $result[] = $answer;
            }
        }
        // 分离普通题目和拍照题目
        $normalQuestions = [];
        $photoQuestions = [];
        foreach ($result as $item) {
            if ($item['type'] == 2) {
                $photoQuestions[] = $item;
            } else {
                $normalQuestions[] = $item;
            }
        }
        // 查询普通题目的题库信息
        if (!empty($normalQuestions)) {
            $questionIds = array_column($normalQuestions, 'question_id');
            $questionUserAnswers = [];
            foreach ($normalQuestions as $answer) {
                $questionUserAnswers[$answer['question_id']] = $answer;
            }
            $question = new Question();
            $questionList = $question->getListQuestion(['id' => $questionIds], $questionUserAnswers);

            // 合并普通题目和拍照题目
            return array_merge($questionList, $photoQuestions);
        }
        // 如果只有拍照题目，直接返回
        return $photoQuestions;
    }
}
